package com.service;

import com.aop.Detach;
import com.model.FrontUser;
import com.model.form.FrontUserForm;
import com.pepository.dao.FrontUserRepository;
import com.utils.Md5Utils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class FrontUserService {

    @Autowired
    private FrontUserRepository userRepository;

    public boolean hasUser(String username) {
        return userRepository.hasByUsername(username) > 0;
    }


    public boolean hasUser(String username, String password) {
        password = Md5Utils.decodeFrontUser(username, password);
        return userRepository.hasByUsername(username, password) > 0;
    }

    //TODO 测试是否能存入数据库
    @Detach
    public FrontUser updateLoginTime(String username, LocalDateTime now) {
        FrontUser user = userRepository.findByUsername(username);
        user.setLoginTime(now);
        return user;
    }

    public void save(FrontUserForm form) {
        FrontUser user = new ModelMapper().map(form, FrontUser.class);
        user.setPassword(Md5Utils.decodeFrontUser(user));
        user.setHangUp(false);
        user.setRegTime(LocalDateTime.now());
        userRepository.save(user);
    }
}
